# Clean up
rm(list = ls())

# Set working directory; please set your own here
setwd("~/Dropbox/Fragmentation/fragmentation_replication_bjps/")

library(tidyverse)
library(foreign)

# Import data with main analyses
data <- read.dta("Results/analyses_final.dta")

# Defining line breaks in the type of outcome
levels(data$outcome_type) <- gsub("\\n", "\n", levels(data$outcome_type))

# Fixing levels in outcome and outcome_type variables
table(data$Outcome)
data$Outcome[data$Outcome == "Summary\\nmeasures (PCA)"] <- "Summary measures (PCA)"
data$Outcome[data$Outcome == "Repr underpriviliged\\ngroups (PCA)"] <- "Repr underpriviliged groups (PCA)"

table(data$outcome_type)
data$outcome_type[data$outcome_type == "Summary\\nmeasures"] <- "Summary\nmeasures"
data$outcome_type[data$outcome_type == "Descriptive\\nrepr of women"] <- "Descriptive\nrepr of women"
data$outcome_type[data$outcome_type == "Repr underpriviliged\\ngroups"] <- "Repr underpriviliged\ngroups"
data$outcome_type[data$outcome_type == "Other\\noutcomes"] <- "Other\noutcomes"

# Creating a variable to order the plot by
data$order_outcome <- 1
data$order_outcome[data$outcome_type == "Summary\nmeasures"] <- 0
data$order_outcome[data$outcome_type == "Other\noutcomes"] <- 2

# Make the plot
main_plot2 <- data %>%
  filter(Instruments == 1) %>%
  filter(Polynomials == 1) %>%
  filter(Sample == "Whole") %>%
  filter(FE == "None") %>%
  filter(Predictor == "Absolute number parl parties") %>%
  mutate(Outcome = fct_reorder(Outcome, pca)) %>%
  mutate(outcome_type = fct_reorder(outcome_type, order_outcome)) %>%
  ggplot(aes(Outcome, Effect, color = factor(pca), show.legend = FALSE)) + 
  geom_hline(aes(yintercept = 0), linetype = 2) + 
  coord_flip(ylim = c(-1.5, 1.5)) + 
  geom_linerange(aes(ymin = ci_lower, ymax = ci_upper), position = position_dodge(width = 0.75) ) + 
  geom_point(size = 1, position = position_dodge(width = 0.75) ) + 
  facet_grid(rows = vars(outcome_type),
             scales = "free_y") + 
  theme_minimal(base_size = 9) +
  theme(legend.position = "none",
        panel.background = element_rect(fill = NA, color = "black")) +
  scale_color_manual(values = c("black", "blue")) +
  ylab(" ") + 
  xlab("") 
main_plot2

# Save the plot
ggsave("Plots/figd8.png", plot = main_plot2, width = 25, height = 20, units = "cm")